<template>
  <div>
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item v-bind:to='{ path: "/" }'>首页</el-breadcrumb-item>
      <el-breadcrumb-item>移动端管理</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class='dict-main'>
      <el-tabs v-model='activeName' class='title-top'>
        <el-tab-pane label='文章管理' name='first'>
          <div class='main-module charger'>
            <el-row class='posre'>
              <el-col :span='12' class='text-right search-top'>
                <el-button size='small' type='success' icon='el-icon-upload' @click='openArtileAddWin()'>发布文章 </el-button>
                <el-button size='small' icon='el-icon-arrow-up' @click='show = !show' plain v-if='show==true'>搜索
                </el-button>
                <el-button size='small' icon='el-icon-arrow-down' @click='show = !show' plain v-else >搜索</el-button>

              </el-col>
            </el-row>
            <el-collapse-transition>
              <div v-show='show'>
                <el-row :gutter='20' class='bill-search'>
                  <el-col :span='12' class='bill-search-row'>
                    <label class='bill-search-title fl'>用户手机</label>
                    <el-input placeholder="输入发布人手机进行搜索" v-model='params.mobile'></el-input>
                  </el-col>
                  <el-col :span='12' class='bill-search-row'>
                    <label class='bill-search-title fl'>用户昵称</label>
                    <el-input placeholder="输入发布人昵称进行搜索" v-model='params.nickName'></el-input>
                  </el-col>
                  <el-col :span='12' class='bill-search-row'>
                    <label class='demonstration bill-search-title fl'>发布日期</label>
                    <div class='block'>
                      <el-date-picker
                        v-model='startDates'
                        value-format='yyyy-MM-dd'
                        type='daterange'
                        align='right'
                        unlink-panels
                        range-separator='至'
                        start-placeholder='开始日期'
                        end-placeholder='结束日期'
                        :picker-options='pickerOptions'>
                      </el-date-picker>
                    </div>
                  </el-col>
                  <el-col :span='14' class='bill-search-row text-right'>
                    <el-button type='warning' size='small' icon='el-icon-search' @click='clearParams()'>清空</el-button>
                    <el-button type='primary' size='small' icon='el-icon-search' @click='searchArticleData()'>检索</el-button>
                  </el-col>
                </el-row>
              </div>
            </el-collapse-transition>
            <!--表格-->
            <template>
              <el-table ref="articleTable" :data='articleData' stripe tooltip-effect='dark' style='width: 100%'
                        @sort-change="createTimeSort" @filter-change="filterHandler">
                <el-table-column label='发布时间' prop='showCreateTime' align='center' min-width="150"
                                 sortable="custom"></el-table-column>
                <el-table-column label='用户类型' prop='showUserType' columnKey="userType" min-width="150"
                                 align='center' :filters="userTypeFilter" :filter-multiple=false>
                </el-table-column>
                <el-table-column label='用户' prop="mobile" min-width="150" align='center'>
                  <template slot-scope="scope">
                    <span>{{scope.row.nickName}}({{scope.row.mobile}})</span>
                  </template>
                </el-table-column>
                <el-table-column label='文章类型' prop='showArticleType'  columnKey="articleType" min-width="120" align='center'
                                 :filters="articleTypeFilter" :filter-multiple=false>
                </el-table-column>
                <el-table-column label='内容' prop='content' min-width="200" align='center' show-overflow-tooltip></el-table-column>
                <el-table-column label='置顶' prop="setTop" min-width="130" align='center'>
                  <template slot-scope="scope">
                    <el-tag type="danger" disable-transitions v-if="scope.row.setTop==1 && scope.row.userType==0">已置顶</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label='状态' prop='status' columnKey="status" min-width="150" show-overflow-tooltip
                                 align='center' :filters="statusFilter" :filter-multiple=false>
                  <template slot-scope="scope">
                    <span v-if="scope.row.status==1">正常</span>
                    <span v-if="scope.row.status==0">冻结</span>
                  </template>

                </el-table-column>
                <el-table-column label="操作" fixed="right" width="240" align="left">
                  <template slot-scope="scope">
                    <el-button size="mini" type="success" plain @click="appArticleDetail(scope.row.articleId)">详情</el-button>
                    <el-button size="mini" type="warning" plain v-if="scope.row.status==1"
                               @click='modifyStatus(scope.row.articleId,0)'>冻结
                    </el-button>
                    <el-button size="mini" type="success" plain v-if="scope.row.status==0"
                               @click='modifyStatus(scope.row.articleId,1)'>解冻
                    </el-button>
                    <el-dropdown class='m-left10' v-if="scope.row.userType==0">
                      <el-button type='primary' size='mini'>
                        更多<i class='el-icon-arrow-down el-icon--right'></i>
                      </el-button>
                      <el-dropdown-menu slot='dropdown'>
                        <el-button size="mini"  v-if="scope.row.setTop==0" type="primary" plain @click="modifySetTop(scope.row.articleId,1)">置顶</el-button>
                        <el-button size="mini"  v-if="scope.row.setTop==1" type="primary" plain @click="modifySetTop(scope.row.articleId,0)">取消置顶</el-button>
                        <el-button size="mini"  type="danger" plain @click="deleteArticle(scope.row.articleId)">删除</el-button>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </template>
            <!--分页-->
            <div class='block text-center'>
              <el-pagination @size-change='handleSizeChange' @current-change='handleCurrentChange'
                             :current-page='pageable.currentPage' :page-sizes='[20, 40, 80, 100]'
                             :page-size='pageable.pageSize' layout='total, sizes, prev, pager, next, jumper'
                             :total='pageable.total'></el-pagination>
            </div>
          </div>

          <!--文章详情-->
          <div>
            <el-dialog title='文章详情' width="600px" :visible.sync='dialogViewVisible'  >
              <el-form label-width='120px'>
                <el-form-item label='发布时间:'>
                  <span>{{articleInfo.showCreateTime}}</span>
                </el-form-item>
                <el-form-item label='文章类型:'>
                  <span>{{articleInfo.showArticleType}}</span>
                </el-form-item>
                <el-form-item label='发布用户:'>
                  <span>{{articleInfo.nickName}} - {{articleInfo.mobile}}</span> （<span>{{articleInfo.showUserType}}</span>）
                </el-form-item>
                <el-form-item label='内容:'>
                  <span>{{articleInfo.content}}</span><br/>
                    <span v-for="media in articleInfo.medias">
                       <img v-if="articleInfo.mediaType==1" style="width: 120px; height: 120px" :src="media.fullMediaPath"
                       />
                      <video style="width: 400px; height: 200px"  v-if="articleInfo.mediaType==2"  :src="media.fullMediaPath" class="avatar" controls="controls"></video>
                  </span>
                </el-form-item>
                <el-form-item label='状态:'>
                  <span>{{articleInfo.status==1?"正常":"冻结"}}</span>
                </el-form-item>
              </el-form>
              <div slot='footer' class='dialog-footer'>
                <el-button type='primary' @click='dialogViewVisible=false'>关闭</el-button>
              </div>
            </el-dialog>
          </div>

          <!--发布文章-->
          <div>
            <el-dialog title='发布文章' width="700px" :visible.sync='dialogAddVisible'  >
              <el-form :model="addForm" :rules="rules" ref="addForm" label-width="120px" label-suffix=":">
                <el-form-item label='发布用户' prop="userId">
                  <el-select v-model="addForm.userId" filterable placeholder="请选择发布用户" style="width:100%">
                    <el-option
                      v-for="user in platUsers"
                      :key="user.userId"
                      :label="user.nickName"
                      :value="user.userId">
                      <span style="float: left">{{ user.nickName }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ user.mobile }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label='文章类型' prop='articleType'>
                  <el-radio-group v-model="addForm.articleType">
                    <el-radio :label="1">普通</el-radio>
                    <el-radio :label="2">活动</el-radio>
                    <el-radio :label="3">资讯</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label='排序' prop='setTop'>
                  <el-radio-group v-model="addForm.setTop">
                    <el-radio :label="0">默认</el-radio>
                    <el-radio :label="1">置顶</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label='文章内容' prop='content'>
                  <el-input type="textarea" rows="5" v-model="addForm.content"></el-input>
                </el-form-item>
                <el-form-item label='多媒体类型' prop='mediaType'>
                  <el-radio-group v-model="addForm.mediaType" @change="mediaTypeChanges">
                    <el-radio :label="0">无</el-radio>
                    <el-radio :label="1">图片</el-radio>
                    <el-radio :label="2">视频</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="addForm.mediaType==1" label='图片上传' prop='logo' >
                  <el-upload
                    :http-request='doUpload'
                    :before-upload='beforeAvatarUpload'
                    action=""
                    :limit="9"
                    :file-list="fileList"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                 <!-- <el-dialog :visible.sync="dialogImageVisible" size="tiny">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>-->
                  <span style="color: red">最多上传9张图片</span>
                </el-form-item>
                <el-form-item label='视频上传' prop='url' v-if="addForm.mediaType==2">
                  <el-upload v-if="videoUrl==''"
                             class="avatar-uploader"
                             action=""
                             :http-request='doVideoUpload'
                             :before-upload='beforeVideoUpload'
                             :show-file-list="false">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                  <video v-if="videoUrl !=''"  style="width: 400px; height: 200px" :src="showVideoUrl" class="avatar" controls="controls"></video>
                  <el-button v-if="videoUrl !=''" type="success" icon="el-icon-upload" @click="reUploadVideo">重新上传</el-button>
                </el-form-item>
              </el-form>
              <div slot='footer' class='dialog-footer'>
                <el-button @click='dialogAddVisible=false'>取消</el-button>
                <el-button type='primary' @click='submitAddForm'>保存</el-button>
              </div>
            </el-dialog>
          </div>

        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
  import {
    loadArticleDatas,
    loadArticleDetail,
    addArticle,
    modifyStatus,
    modifySetTop,
    deleteArticle
  } from '@/api/article';
  import { uploadOss } from '@/api/image-oss';
  import { getOSSProperties, insertImage } from '@/api/image';
  import { loadPlatAppUsers } from '@/api/app-user';
  export default {
    data() {
      return {
        ossProperties: {},
        baseDir: 'steach/app-user',
        medias: [],
        fileList: [],
        dialogImageUrl: '',
        videoUrl: '',
        showVideoUrl: '',
        dialogImageVisible: false,
        dialogViewVisible: false,
        dialogAddVisible: false,
        dialogEditVisible: false,
        show: false,
        pageable: {
          currentPage: 1,
          pageSize: 20
        },
        activeName: 'first',
        platUsers: [],
        articleData: [], //列表数据
        articleInfo: '',//文章详情
        startDates: '',
        userTypeFilter: [
          {
            text: '普通用户', value: '1'
          },
          {
            text: '平台用户', value: '0'
          }],
        articleTypeFilter: [
          {
            text: '普通', value: '1'
          },
          {
            text: '活动', value: '2'
          },
          {
            text: '资讯', value: '3'
          }],
        statusFilter: [
          {
            text: '正常', value: '1'
          },
          {
            text: '冻结', value: '0'
          }],
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }
          ]
        },
        params: {
          page: 1,
          size: 20,
          userType: '',
          mobile: '',
          nickName: '',
          articleType: '',
          setTop: '',
          status: '',
          startDate: '',
          endDate: '',
          createTimeSort: '2'
        },
        addForm: {
          userId: '',
          articleType: '1',
          content: '',
          mediaType: '0',
          setTop: '0',
          medias: []
        },
        rules: {
          userId: [
            {required: true, message: '请选择发布用户', trigger: 'blur'}
          ],
          articleType: [
            {required: true, message: '请选择文章类型', trigger: 'blur'}
          ],
          mediaType: [
            {required: true, message: '请选择媒体文件类型', trigger: 'blur'}
          ],
          content: [
            {required: true, message: '请输入文章类容', trigger: 'blur'},
            {min: 10, max: 500, message: '请输入10-500字符', trigger: 'blur'}
          ]
        }
      };
    },
    filters: {},
    methods: {
      //获取数据
      loadArticleDatas() {
        this.params.page = this.pageable.currentPage;
        this.params.size = this.pageable.pageSize;
        if (this.startDates != null) {
          this.params.startDate = this.startDates[0];
          this.params.endDate = this.startDates[1];
        }
        loadArticleDatas(this.params).then(response => {
          if (response.code !== 0) {
            this.$message({
              message: response.message,
              type: 'error'
            });
          } else {
            this.articleData = response.data.data;
            this.pageable = {
              currentPage: response.data.pageInfo.page,
              pageSize: response.data.pageInfo.pageSize,
              total: response.data.pageInfo.total
            };
          }
        });
      },
      //搜索
      searchArticleData() {
        this.loadArticleDatas();
      },
      clearParams() {
        this.params = {};
        this.startDates = [];
      },
      //申请时间排序
      createTimeSort(params) {
        if (params.prop == 'showCreateTime') {
          if (params.order == 'ascending') {
            this.params.createTimeSort = 1;
          } else if (params.order == 'descending') {
            this.params.createTimeSort = 2;
          }
        }
        this.loadArticleDatas();
      },
      //状态筛选 用户类型筛选
      filterHandler(filter) {
        if(filter.userType!=null && this.params.userType != filter.userType[0]){
          this.params.userType = filter.userType[0];
        }
        if(filter.articleType!=null && this.params.articleType != filter.articleType[0]){
          this.params.articleType = filter.articleType[0];
        }
        if(filter.status!=null && this.params.status != filter.status[0]){
          this.params.status = filter.status[0];
        }
        this.loadArticleDatas();
      },
      //分页
      handleSizeChange(val) {
        this.pageable.pageSize = val;
        this.loadArticleDatas();
      },
      handleCurrentChange(val) {
        this.pageable.currentPage = val;
        this.loadArticleDatas();
      },
      appArticleDetail(articleId){
        loadArticleDetail(articleId).then(response => {
          if (response.code !== 0) {
            this.$message({
              message: response.message,
              type: 'error'
            });
          } else {
            this.dialogViewVisible=true;
            this.articleInfo = response.data;
          }
        });
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogImageVisible = true;
      },
      handleRemove(file, fileList) {
        var _this = this;
        var uid = file.uid;
        var medias =_this.medias;
        var f =_this.fileList;

        var deluid;
        var farr = [];
        f.forEach(function (p) {
          if(p.uid != uid){
            farr.push(p);
          }else{
            deluid = p.name;
          }
        });
        _this.fileList = farr;

        var parr = [];
        medias.forEach(function (p) {
          if(p.uid != deluid){
            parr.push(p);
          }
        });
        _this.medias = parr;
      },
      beforeAvatarUpload (file) {
          const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
          const isLt2M = file.size / 1024 / 1024 < 10;

          if (!isJPG) {
            this.$message.error('上传logo图片只能是 JPG 格式!');
          }
          if (!isLt2M) {
            this.$message.error('上传logo图片大小不能超过 10MB!');
          }
          return isJPG && isLt2M;
      },
      beforeVideoUpload (file){
        const isMP4 = file.type === 'video/mp4';
        const isLt30M = file.size / 1024 / 1024 < 30;
        if (!isMP4) {
          this.$message.error('上传的视频只能是MP4格式!');
        }
        if (!isLt30M) {
          this.$message.error('上传的视频不能超过30MB!');
        }
        return isMP4 && isLt30M;
      },
      doUpload(file){
        var _this = this;
        uploadOss(_this.ossProperties, file, function (url) {
          insertImage(url).then(res => {
            var f = file.file;
            _this.medias.push({
              uid: f.uid,
              id: res.data.id,
              path: res.data.path
            });
            _this.fileList.push({
              name: f.uid,
              url: _this.ossProperties.showUrl + res.data.path
            });
          });
        });
      },
      doVideoUpload(file){
        var _this = this;
        const loading = this.$loading({
          lock: true,
          text: '正在上传',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        uploadOss(_this.ossProperties, file, function (url) {
          insertImage(url).then(res => {
            loading.close();
            _this.videoUrl = res.data.path;
            _this.showVideoUrl = _this.ossProperties.showUrl + res.data.path;
          });
        });
      },
      reUploadVideo(){
        this.videoUrl = '';
        this.showVideoUrl = '';
      },
      openArtileAddWin() {
        this.dialogAddVisible = true;
        this.addForm= {
          userId: '',
          articleType: 1,
          content: '',
          mediaType: 0,
          setTop: 0,
          medias: []
        }
      },
      mediaTypeChanges(value){
        this.fileList=[];
        this.medias=[];
        this.videoUrl = '';
        this.showVideoUrl = '';
      },
      submitAddForm(){
        var that = this;
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            if(that.addForm.mediaType==1){
              that.medias.forEach(function(item){
                that.addForm.medias.push(item.path);
              })
            }else{
              that.addForm.medias.push(that.videoUrl);
            }
            addArticle(that.addForm).then(response => {
              if (response.code == 0) {
                this.$message({
                  message: '文章发布成功',
                  type: 'success'
                });
                that.dialogAddVisible= false;
                that.loadArticleDatas();
              } else {
                this.$message({
                  message: response.message,
                  type: 'error'
                });
              }
            });
          } else {
            return false;
          }
        })
      },
      modifyStatus(articleId,status){
        var that = this;
        this.$confirm('确定要'+(status==0?'冻结':'解冻')+'该文章吗，是否继续操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          modifyStatus(articleId).then(response => {
            if (response.code == 0) {
              that.$message({
                message: (status==0?'冻结':'解冻')+'成功',
                type: 'success'
              });
              that.loadArticleDatas();
            } else {
              that.$message({
                message: response.message,
                type: 'error'
              });
            }
          });
        });
      },
      modifySetTop(articleId,setTop){
        var that = this;
        this.$confirm('确定要'+(setTop==0?'取消置顶':'置顶')+'该文章吗，是否继续操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          modifySetTop(articleId).then(response => {
            if (response.code == 0) {
              that.$message({
                message: (setTop==0?'取消置顶':'置顶')+'成功',
                type: 'success'
              });
              that.loadArticleDatas();
            } else {
              that.$message({
                message: response.message,
                type: 'error'
              });
            }
          });
        });
      },
      deleteArticle(articleId){
        var that = this;
        this.$confirm('确定要删除该文章吗，改操作不可逆，是否继续操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteArticle(articleId).then(response => {
            if (response.code == 0) {
              that.$message({
                message: '删除成功',
                type: 'success'
              });
              that.loadArticleDatas();
            } else {
              that.$message({
                message: response.message,
                type: 'error'
              });
            }
          });
        });
      }
    },
    watch: {},
    created: function () {
      this.loadArticleDatas();
      getOSSProperties(this.baseDir).then(response => {
        if(response.code == 0){
          this.ossProperties = response.data;
        }else{
          this.$message({
            message: response.message,
            type: 'error'
          });
        }
      });
      loadPlatAppUsers().then(response => {
        if(response.code == 0){
          this.platUsers = response.data;
        }else{
          this.$message({
            message: response.message,
            type: 'error'
          });
        }
      })
    }
  };
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    float: left;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    /*font-size: 28px;*/
    color: #8c939d;
    width: 133px;
    height: 133px;
    line-height: 133px;
    text-align: center;
  }
  .avatar {
    width: 133px;
    height: 133px;
    display: block;
  }
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: '';
  }

  .clearfix:after {
    clear: both
  }
</style>

